#封装请求以及其他通用的方法比如get post

import requests
import json
# from common.read_yaml import ReadYamlConfigs
from common.readconfig import env
import time
from urllib.parse import urlencode
import allure
# data = ReadYamlConfigs('data.yaml').get_yaml_data()#读取config下的data数据
from common.read_yaml import get_yaml_filepath
from common.readconfig import Environ
data = get_yaml_filepath(Environ=Environ)
class HttpClient:
    def __init__(self):
        self.host = data['admin_host']
        # print(self.host)

    default_header = {"Content-Type":"application/json"}

    def send(self,url,body = {},method ={},headers ={},x_token = " ",sessions = " "):
         headers.update(self.default_header)
         # print(headers)


         if x_token:
             headers["Authorization"] = "Bearer " + x_token
         if sessions:
             headers["session"] = "Bearer " + sessions

         if method == "get":
             result = requests.get(url,params = body,headers = headers)
         elif method == "post":
             result = requests.post(url,data = json.dumps(body),headers = headers)
             # print("777:",result.json())
             # requests.post(url, json=body, headers=headers)
         elif method == "patch":
             result = requests.patch(url, data=json.dumps(body), headers=headers)
         self.creat_request_log(url,method,body,headers)
         self.creat_response_log(result.status_code,result.json())

         return result.json()

    def get_full_url(self,url,etc = {},replace = {},h = ""):

        if h:
            host = h.rstrip('/')  #rstrip 删除string 字符串末尾的指定字符（默认空格）
        else:
            host = self.host.rstrip()

        url = url.lstrip('/') #lstrip 用于截掉字符串左边的空格或者指定字符
        full_url = host + "/" + url
        full_url += "?platform={}&time=".format(env) + str(int(time.time()*1000))

        if etc:
            s = urlencode(etc) #urlencode 可以把key-value这样的键值对转换成我们想要的格式，返回的是a=1&b=2这样的字符串
            full_url += "&" +s

        if replace:
            full_url = str.format(full_url,replace) #str.format() 方法通过字符串中的{}来识别替换字段 ，从而完成字符串的格式化

        return full_url

    @allure.step("请求日志")
    def creat_request_log(self,url,methed,body,headers):
        pass
        # print("请求日志：",url,methed,body,headers)

    @allure.step("响应日志")
    def creat_response_log(self,status_code,text):
        pass
        # print("响应日志：",status_code,text)

if __name__ == '__main__':
    clent = HttpClient()
    re = clent.send(url='http://121.37.169.128:8201/mall-member/sso/login?password=123456&username=admin',
                    method="post")
